<?php

namespace app\controllers;

use Yii;
use yii\base\Exception;
use yii\helpers\VarDumper;
use yii\web\Controller;
use app\models\TBaseDevice;
use app\models\CourseInfo;
use app\models\CourseItem;
use app\models\TCourseItem;
use app\models\CourseKnowledge;
use app\models\TCourseInfo;
use app\models\BCourseItemResource;
use app\controllers\BaseController;
use app\models\TBaseClassMember;
use app\models\TCourseNote;
use app\models\BCourseInfo;
use app\models\BCourseItem;
use app\models\TCourseMember;
use Faker\Provider\Uuid;
use app\models\TQuizPaperRelation;
use app\models\TQuizPaperQuesRelation;
use app\models\TCourseScheduleQuiz;
use app\models\TQuizResult;
use app\models\BExamine;
use app\models\BCourseAuthor;
use yii\helpers\Html;
use app\common\ArrayHelper;
use app\models\TCourseSigninInfo;
use app\models\TCourseSigninStudent;
use app\models\TBaseUserProfile;
use app\models\TCourseTask;
use app\models\TCourseTaskList;
use app\common\PdUtils;


class ClassroomTaskController extends Controller{
    public $enableCsrfValidation = false;
    public function init(){
        parent::init();
        header('Access-Control-Allow-Origin: *');
    }
    /**
 * 实训任务列表(课前,课中,课后)
 * @param courseId 课程ID,scheduleId 课表ID,studyType 课表类型(课前,课中,课后),taskStatus 测验状态(已发布/未发布)
 * 
 */
    public function actionGetTaskList(){
        $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $scheduleId= isset($_REQUEST['scheduleId'])?$_REQUEST['scheduleId']:$error[]=array('课表ID不能为空');
        $studyType= isset($_REQUEST['studyType'])?$_REQUEST['studyType']:$error[]=array('课表类型不能为空');
        $taskStatus= isset($_REQUEST['taskStatus'])?$_REQUEST['taskStatus']:$error[]=array('实训任务状态不能为空');
        $pageSize   = isset($_REQUEST['pageSize']) && !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
        $page       = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page']:'1';
        $offset     = ($page-1)*$pageSize;
        $limit      = "limit ".$offset.",$pageSize";
        if(!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $where = "";
            if($taskStatus=='activityStatus.checked'|| $taskStatus=='activityStatus.new'){//未发布
                $where = " and st.status in('activityStatus.checked','activityStatus.new')";
            }else{//已发布
                $where = " and st.status in('activityStatus.ongoing','activityStatus.over')";
            }
            $sql="SELECT
    t.id,t.task_title,t.task_goal,p.pet_name,i.name as course_name,st.status
FROM
    t_course_task t
LEFT JOIN t_course_schedule_task st ON t.id = st.task_id
LEFT JOIN t_base_user_profile p ON t.create_by=p.user_id
LEFT JOIN t_course_info i ON i.id=t.t_course_id
WHERE
    st.del_flag = 0
AND t.del_flag=0
AND st.t_course_id =:t_course_id
AND st.t_course_schedule_id =:t_course_schedule_id and study_type=:study_type ".$where."  ORDER BY t.create_time,t.task_title ".$limit;
            $taskList=\yii::$app->db->createCommand($sql)->bindValues([':t_course_id'=>$courseId,':t_course_schedule_id'=>$scheduleId,':study_type'=>$studyType])->queryAll();
            foreach($taskList as $k=>&$v){
                $sql="select count(*) from t_course_task_list where task_id=:task_id and del_flag=0";
                $taskNum=\yii::$app->db->createCommand($sql)->bindValues([':task_id'=>$v['id']])->queryScalar();
                $v['group']=($taskNum==1) ? 'yesOrNo.no' : 'yesOrNo.yes';
                //任务状态
                if($v['status']!='activityStatus.ongoing'){
                    //未发布
                    $v['status']='';//未发布状态为空串
                }else{
                    //已发布则查询完成情况
                    $sql="select count(*) as allNum from t_course_task_report where del_flag=0 and course_id=:course_id and task_id=:task_id and schedule_id=:schedule_id";
                    $allNum=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$courseId,':task_id'=>$v['id'],':schedule_id'=>$scheduleId])->queryScalar();
                    $sql="select count(*) as completeNum from t_course_task_report where del_flag=0 and course_id=:course_id and task_id=:task_id and schedule_id=:schedule_id and report_status!='reportStatus.notComplete'";
                    $completeNum=\yii::$app->db->createCommand($sql)->bindValues([':course_id'=>$courseId,':task_id'=>$v['id'],':schedule_id'=>$scheduleId])->queryScalar();
                    if($completeNum==0){
                        $v['status']='待批阅';
                    }else if($completeNum>0 && $completeNum<$allNum){
                        $v['status']='批阅中';
                    }else if($completeNum==$allNum){
                        $v['status']='已批阅';
                    }
                }
            }
            if(count($taskList)==0){
                $result = array(
                    "msg" => "没有查询到相关数据",
                    "ver" => "1.5.0",
                    'data' => [],
                    'code' => '404'
                );
            }else{
                $result = array(
                    "msg" => "查找成功",
                    "ver" => "1.5.0",
                    'data' => ArrayHelper::array_is_null($taskList),
                    'code' => '200'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }

    /**
 * 导入实训任务列表
 * @param courseId 课程ID  taskTitle 检索任务名称
 * 
 */
 public function actionImportTaskList(){
    $error = array();
        $courseId = isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $taskTitle = isset($_REQUEST['taskTitle'])?$_REQUEST['taskTitle']:'';
        $pageSize   = isset($_REQUEST['pageSize']) && !empty($_REQUEST['pageSize']) ? $_REQUEST['pageSize'] : '20';
        $page       = isset($_REQUEST['page']) && !empty($_REQUEST['page']) ? $_REQUEST['page']:'1';
        $offset     = ($page-1)*$pageSize;
        $limit      = "limit ".$offset.",$pageSize";
        if(!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            //查询开课对应的模板课id
            $sql="select b_course_info_id from t_course_info where del_flag=0 and id=:courseId";
            $bcourseId=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$courseId])->queryScalar();
            $where="";
            if(!empty($taskTitle)){
                $where.=" AND t.task_title like '%".$taskTitle."%' ";
            }
            if(!empty($bcourseId)){
                        $sql="SELECT
    t.id,
    t.task_title,
    t.task_goal,
    p.pet_name,
    i.name as course_name
FROM
    t_course_task t
    LEFT JOIN t_base_user_profile p ON p.user_id = t.create_by
  LEFT JOIN b_course_info i on i.id=t.b_course_id
WHERE
    t.del_flag = 0 
    AND t.b_course_id =:bcourseId
    AND t.task_status = 'activityStatus.checked' 
    AND t.template_id IS NULL 
    AND t.t_course_id IS NULL ".$where."
ORDER BY
    t.create_time DESC  ".$limit;
                     $taskList=\yii::$app->db->createCommand($sql)->bindValues([':bcourseId'=>$bcourseId])->queryAll();
                     foreach ($taskList as $key => &$value) {
                            $sql="select count(*) from t_course_task_list where task_id=:task_id and del_flag=0";
                            $taskNum=\yii::$app->db->createCommand($sql)->bindValues([':task_id'=>$value['id']])->queryScalar();
                            $value['group']=($taskNum==1) ? 'yesOrNo.no' : 'yesOrNo.yes';
                     }
                    if (!empty($taskList)) {
                        $result = array(
                            "msg" => "查找成功",
                            "ver" => "1.5.0",
                            'data' => ArrayHelper::array_is_null($taskList),
                            'code' => '200'
                        );
                    } else {
                        $result = array(
                            "msg" => "没有查询到相关数据",
                            "ver" => "1.5.0",
                            'data' => [],
                            'code' => '404'
                        );
                    }
        }else{
                  $result = array(
                        "msg" => "bcourseId不存在",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '400'
                    );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * 删除实训任务
     * @param   taskId 实训任务id scheduleId 课表Id
     * 
     */
    public function actionDeleteTask(){
        $error = array();
        $courseId= isset($_REQUEST['courseId'])?$_REQUEST['courseId']:$error[]=array('课程ID不能为空');
        $scheduleId= isset($_REQUEST['scheduleId'])?$_REQUEST['scheduleId']:$error[]=array('课表ID不能为空');
        $taskId= isset($_REQUEST['taskId'])?$_REQUEST['taskId']:$error[]=array('任务ID不能为空');
        if(!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => $error,
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $sql="UPDATE t_course_schedule_task
SET del_flag = 1
WHERE
    t_course_id =:courseId
AND t_course_schedule_id =:schedule_id
AND task_id=:task_id";
        $res=\yii::$app->db->createCommand($sql)->bindValues([':courseId'=>$courseId,':schedule_id'=>$scheduleId,':task_id'=>$taskId])->execute();
        if($res){
                //没有学生完成该任务时删除报告单
                $sql="select * from t_course_task_report where task_id=:id AND del_flag=0 and course_id=:courseId and schedule_id=:schedule_id";
                $res=Yii::$app->db->createCommand($sql)->bindValues([':id'=>$taskId,':schedule_id'=>$scheduleId,':courseId'=>$courseId])->queryAll();
                if($res){
                  //删除已有报告单
                  $sql="update t_course_task_report set del_flag=1,update_time=:update_time where task_id=:id and course_id=:courseId and schedule_id=:schedule_id";
                  Yii::$app->db->createCommand($sql)->bindValues([':update_time'=>date('Y-m-d H:i:s'),':id'=>$taskId,':schedule_id'=>$scheduleId,':courseId'=>$courseId])->execute();
                }
                 $result = array(
                        "msg" => "删除成功",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '200'
                );
            }else{
                $result = array(
                        "msg" => "删除失败，任务不存在",
                        "ver" => "1.5.0",
                        'data' => [],
                        'code' => '400'
                );
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP课堂教学新建任务接口
     * @param int  userId:教师ID tcourseId:课程ID title:标题 goal:目标 content:内容 fileId：附件ID taskSon：子任务 token:token projectId:联盟ID
     * @param string  start_time:开始时间 end_time:结束时间 code:签到码
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-2-28
     * @author: gyq
     */
    public function actionAppAddNewTask(){
        $error      = array();
        $userId     = isset($_REQUEST['userId']) && !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error[]='教师id不能为空';
        $tcourseId  = isset($_REQUEST['tcourseId']) && !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error[]='课程id不能为空';
        $title      = isset($_REQUEST['title']) && !empty($_REQUEST['title']) ? $_REQUEST['title'] : $error[]='标题不能为空';
        $goal       = isset($_REQUEST['goal']) && !empty($_REQUEST['goal']) ? $_REQUEST['goal'] : $error[]='任务目标不能为空';
        $content    = isset($_REQUEST['content']) && !empty($_REQUEST['content']) ? $_REQUEST['content'] : $error[]='内容不能为空';
        $fileId     = isset($_REQUEST['fileId']) && !empty($_REQUEST['fileId']) ? $_REQUEST['fileId'] : '';
        $taskSon    = isset($_REQUEST['taskSon']) && !empty($_REQUEST['taskSon']) ? json_decode($_REQUEST['taskSon'],true) : '';
        $projectId  = isset($_REQUEST['projectId']) && !empty($_REQUEST['projectId']) ? $_REQUEST['projectId'] : $error[]='联盟ID不能为空';
        $studyType  = isset($_REQUEST['studyType']) && !empty($_REQUEST['studyType']) ? $_REQUEST['studyType'] : $error[]='课表阶段不能为空';
        $scheduleId = isset($_REQUEST['scheduleId']) && !empty($_REQUEST['scheduleId']) ? $_REQUEST['scheduleId'] : $error[]='课表ID不能为空';
        if (!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $uuid = Uuid::uuid();
            $create_time = date("Y-m-d H:i:s");
            $flag = false;
            try {
                $transaction = Yii::$app->db->beginTransaction();
                $model = new TCourseTask();
                $model->id = $uuid;
                $model->task_title = $title;
                $model->task_goal = $goal;
                $model->task_content = $content;
                $model->t_course_id = $tcourseId;
                $model->b_course_id = TCourseInfo::findOne($tcourseId)->b_course_info_id;
                $model->template_id = '';
                $model->is_public = 'yesOrNo.yes';
                $model->create_by = $userId;
                $model->create_time = $create_time;
                $model->task_status = 'activityStatus.checked';
                $model->del_flag = 0;
                $model->old_id = $uuid;
                if ($model->validate() && $model->save()) {
                    if (!empty($taskSon)) {
                        $taskSonModel = new TCourseTaskList();
                        foreach ($taskSon as $key => $value) {
                            $sonUuid = Uuid::uuid();
                            $sonModel = clone $taskSonModel;
                            $sonModel->id = $sonUuid;
                            $sonModel->task_id = $uuid;
                            $sonModel->task_title = $value['son_title'];
                            $sonModel->task_content = $value['son_content'];
                            $sonModel->create_by = $userId;
                            $sonModel->create_time =$create_time;
                            $sonModel->task_status = 'activityStatus.checked';
                            $sonModel->del_flag = 0;
                            if ($sonModel->validate() && $sonModel->save()) {
                                $flag = true;
                            } else {
                                $flag = false;
                                break;
                            }
                        }
                    } else {
                        $sonUuid = Uuid::uuid();
                        $sonModel = new TCourseTaskList();
                        $sonModel->id = $sonUuid;
                        $sonModel->task_id = $uuid;
                        $sonModel->task_title = $title;
                        $sonModel->task_content = $content;
                        $sonModel->create_by = $userId;
                        $sonModel->create_time =$create_time;
                        $sonModel->task_status = 'activityStatus.checked';
                        $sonModel->del_flag = 0;
                        if ($sonModel->validate() && $sonModel->save()) {
                            $flag = true;
                        }
                    }
                    if (!empty($fileId)) {
                        $fids = explode(',',$fileId);
                        foreach ($fids as $key=>$value) {
                            $sql = "UPDATE t_course_task_upload_file SET task_id=:task_id,update_by=:uid,update_time=:update_time WHERE id=:id";
                            \yii::$app->db->createCommand($sql)->bindValues([':task_id'=>$model->id,':uid'=>$userId,':update_time'=>$create_time,':id'=>$value])->execute();
                        }
                    }
                    //课表任务关联
                    $sql="INSERT INTO t_course_schedule_task (
	id,
	t_course_id,
	t_course_schedule_id,
        status,
        study_type,
	task_id,
	create_by,
	create_time,
	del_flag
)
VALUES
	(
		:id ,:t_course_id ,:t_course_schedule_id ,:status,:study_type,:task_id ,:create_by ,:create_time,0
	)";
                    $res=\yii::$app->db->createCommand($sql)->bindValues([
                        ':id'=>Uuid::uuid(),
                        ':t_course_id'=>$tcourseId,
                        ':t_course_schedule_id'=>$scheduleId,
                        ':status'=>'activityStatus.checked',
                        ':study_type'=>$studyType,
                        ':task_id'=>$uuid,
                        ':create_by'=>$userId,
                        ':create_time'=>$create_time,
                    ])->execute();
                    if(!$res){
                        $flag = false;
                    }
                    if ($flag) {
                        $transaction->commit();
                        $result = [
                            'msg' => '保存成功',
                            'ver' => '1.5.0',
                            'data' => [],
                            'code' => '200'
                        ];
                    } else {
                        $transaction->rollback();
                        $result = [
                            'msg' => '保存失败',
                            'ver' => '1.5.0',
                            'data' => [],
                            'code' => '400'
                        ];
                    }
                } else {
                    $transaction->rollback();
                    $result = [
                        'msg' => '保存失败',
                        'ver' => '1.5.0',
                        'data' => [],
                        'code' => '400'
                    ];
                }
                Yii::$app->end(json_encode($result));
            } catch (Exception $e) {
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400'
                ];
                Yii::$app->end(json_encode($result));
            }
        }
    }
    /*
 * 新建任务附件上传
 */
    public function actionAppNewTaskFiles(){
        $error = array();
        $userId = empty($_REQUEST['userId'])?$error[]=array('用户ID不能为空'):$_REQUEST['userId'];
        $courseId = empty($_REQUEST['courseId'])?$error[]=array('课程ID不能为空'):$_REQUEST['courseId'];
        if (!empty($error)) {
            $result = array(
                "msg"=> "缺少参数",
                "ver"=> "1.5.0",
                'data'=>$error,
                'code'=>'601'
            );
            Yii::$app->end(json_encode($result));
        } else {
            if(!empty($_FILES)){
                $projectId = TCourseInfo::findOne($courseId)['project_id'];
                if (!empty($projectId)) {
                    $path = 'files'.DIRECTORY_SEPARATOR.$projectId.DIRECTORY_SEPARATOR.'course'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'task'.DIRECTORY_SEPARATOR;
                } else {
                    $path = 'files'.DIRECTORY_SEPARATOR.'course'.DIRECTORY_SEPARATOR.$courseId.DIRECTORY_SEPARATOR.'task'.DIRECTORY_SEPARATOR;
                }
                if (!is_dir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path)) {
                    mkdir(\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$path, 0777, true);
                }
                $fileformat =  substr($_FILES['files']["name"], strrpos($_FILES['files']["name"], '.')+1);
                $uri = $path.md5($_FILES['files']["name"]. time()).'.'.$fileformat;
                if (move_uploaded_file($_FILES['files']["tmp_name"],\Yii::$app->params['fileSaveUrl'].DIRECTORY_SEPARATOR.$uri)) {
                    $model = new \app\models\TCourseTaskUploadFile();
                    $model->id = Uuid::uuid();
                    $model->name = $_FILES['files']["name"];
                    $model->file_uri = $uri;
                    $model->size = $_FILES['files']["size"];
                    $model->create_by = $userId;
                    $model->create_time = date('Y-m-d H:i:s', time());
                    $model->type = $fileformat;
                    $model->mime = $_FILES['files']["type"];
                    $model->del_flag = 0;
                    if ($model->validate() && $model->save()) {
                        $arr = array(
                            'fid' => $model->attributes['id'],
                            'filename' => $_FILES['files']["name"],
                            'url' => Yii::$app->params['fileUrl'].$uri
                        );
                        $result = array(
                            "msg"=> "保存成功",
                            "ver"=> "1.5.0",
                            'data'=> $arr,
                            'code'=>'200'
                        );
                    } else {
                        $result = array(
                            "msg"=> "保存失败",
                            "ver"=> "1.5.0",
                            'data'=>array(),
                            'code'=>'400'
                        );
                    }
                } else {
                    $result = array(
                        "msg"=> "保存失败",
                        "ver"=> "1.5.0",
                        'data'=>array(),
                        'code'=>'400'
                    );
                }
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP课堂教学导入实训任务
     * @param int  bcourseId:模板课程ID tcourseId:开课Id  userId:用户ID scheduleId 课表Id studyType 课表类型(课前,课中,课后)
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-02
     * @author: gyq
     */
    public function actionAppImportTaskList(){
        $error      = array();
        $bcourseId  = !empty($_REQUEST['bcourseId'])?$_REQUEST['bcourseId']:$error=array('模板课id不能为空');
        $tcourseId  = !empty($_REQUEST['tcourseId'])?$_REQUEST['tcourseId']:$error=array('开课id不能为空');
        $userId     = !empty($_REQUEST['userId'])?$_REQUEST['userId']:$error=array('用户id不能为空');
        $taskId     = !empty($_REQUEST['taskId'])?$_REQUEST['taskId']:$error=array('任务id不能为空');
        $scheduleId  = !empty($_REQUEST['scheduleId'])?$_REQUEST['scheduleId']:$error=array('课表id不能为空');
        $studyType  = !empty($_REQUEST['studyType'])?$_REQUEST['studyType']:$error=array('课表阶段不能为空');
        $projectId  = !empty($_REQUEST['projectId'])?$_REQUEST['projectId']:$error=array('联盟id不能为空');
        if (!empty($error)) {
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' => [],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        } else {
            $transaction = Yii::$app->db->beginTransaction();
            $flag = 0;
            try{
                $create_time = date('Y-m-d H:i:s',time());
                $uuid = Uuid::uuid();
                //添加实训任务主任务
                $sql = "INSERT INTO t_course_task (
                        id,t_course_id,b_course_id,template_id,task_title,task_goal,task_content,task_score,task_experience,task_status,is_public,create_by,create_time,del_flag
                    ) SELECT
                        '".$uuid."',
                        '".$tcourseId."' AS t_course_id,
                        '".$bcourseId."' AS b_course_id,
                        id AS template_id,
                        task_title AS task_title,
                        task_goal as task_goal,
                        task_content,
                        task_score,
                        task_experience,
                        task_status,
                        is_public,
                        '".$userId."',
                        '".$create_time."',
                        0
                    FROM
                        t_course_task
                    WHERE
                        id = '".$taskId."'";
                $res=Yii::$app->db->createCommand($sql)->execute();
                if(!$res){
                    $flag = 1;
                }
                //添加子任务
                $sql = "SELECT * FROM t_course_task_list WHERE task_id='".$taskId."' AND del_flag=0 ORDER BY create_time asc";
                $res = Yii::$app->db->createCommand($sql)->queryAll();
                if (!$res) {
                    $flag = 1;
                }
                foreach ($res as $k=>$v) {
                    $sql="INSERT INTO t_course_task_list (
                        id,
                        task_id,
                        task_title,
                        task_content,
                        task_status,
                        create_by,
                        create_time,
                        del_flag
                    )
                    VALUES
                        (:uuid,
                         :task_id,
                         :task_title,
                         :task_content,
                         :task_status,
                         :create_by,
                         :create_time,
                         0
                        )";
                    $res=Yii::$app->db->createCommand($sql)->bindValues([
                        ':uuid'=>Uuid::uuid(),
                        ':task_id'=>$uuid,
                        ':task_title'=>$v['task_title'],
                        ':task_content'=>$v['task_content'],
                        ':task_status'=>$v['task_status'],
                        ':create_by'=>$userId,
                        ':create_time'=>$create_time
                    ])->execute();
                    if(!$res){
                        $flag=1;
                    }
                }
                //处理任务附件问题
                $sql = "SELECT * FROM t_course_task_upload_file WHERE del_flag=0 AND task_id=:task_id";
                $taskFile = \yii::$app->db->createCommand($sql)->bindValues([':task_id'=>$taskId])->queryAll();
                if (!empty($taskFile)) {
                    foreach($taskFile as $key => $value){
                        $model = new \app\models\TCourseTaskUploadFile;
                        $model->id = Uuid::uuid();
                        $model->task_id = $uuid;
                        $model->file_uri = $value['file_uri'];
                        $model->name = $value['name'];
                        $model->mime = $value['mime'];
                        $model->size = $value['size'];
                        $model->type = $value['type'];
                        $model->create_by = $userId;
                        $model->create_time = $create_time;
                        $model->del_flag = 0;
                        if ($model->save() && $model->validate()) {
                            //任务附件保存成功
                        }else{
                            $flag=1;
                        }
                    }
                }
                //课堂任务关联表保存数据
                $sql="INSERT INTO t_course_schedule_task (
	id,
	t_course_id,
	t_course_schedule_id,
        status,
        study_type,
	task_id,
	create_by,
	create_time,
	del_flag
)
VALUES
	(
		:id ,:t_course_id ,:t_course_schedule_id ,:status,:study_type,:task_id ,:create_by ,:create_time,0
	)";
                $res=\yii::$app->db->createCommand($sql)->bindValues([
                    ':id'=>Uuid::uuid(),
                    ':t_course_id'=>$tcourseId,
                    ':t_course_schedule_id'=>$scheduleId,
                    ':status'=>'activityStatus.checked',
                    ':study_type'=>$studyType,
                    ':task_id'=>$uuid,
                    ':create_by'=>$userId,
                    ':create_time'=>$create_time,
                ])->execute();
                if(!$res) $flag=1;
            } catch (Exception $e) {
                $result = [
                    'msg' => '保存失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag==0) {
                $transaction->commit();
                $result = [
                    'msg' => '操作成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200'
                ];
            } else {
                $transaction->rollback();
                $result = [
                    'msg' => '操作失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
    /**
     * APP课堂教学发布实训任务
     * @param int  startTime:开始答题时间 deadline：最晚交卷时间 taskId:任务id classIds：班级ID  userId:用户ID scheduleId 课表ID tcourseId 开课ID
     * @return mixed 错误返回NULL，正确返回json
     * @date: 2020-03-02
     * @author: gyq
     */
    public function actionAppReleaseTask(){
        $error      = array();
        $userId     = !empty($_REQUEST['userId']) ? $_REQUEST['userId'] : $error=array('教师id不能为空');
        $taskId     = !empty($_REQUEST['taskId']) ? $_REQUEST['taskId'] : $error=array('任务id不能为空');
        $class_ids  = !empty($_REQUEST['classIds']) ? $_REQUEST['classIds'] : $error=array('班级id不能为空');
        $scheduleId  = !empty($_REQUEST['scheduleId']) ? $_REQUEST['scheduleId'] : $error=array('课表id不能为空');
        $tcourseId  = !empty($_REQUEST['tcourseId']) ? $_REQUEST['tcourseId'] : $error=array('开课id不能为空');
        $startTime  = !empty($_REQUEST['startTime']) ? $_REQUEST['startTime'] : '0000-00-00 00:00:00';
        $deadline   = !empty($_REQUEST['deadline']) ? $_REQUEST['deadline'] : '0000-00-00 00:00:00';
        $projectId  = !empty($_REQUEST['projectId'])?$_REQUEST['projectId']:$error=array('联盟不能为空');
        if(!empty($error)){
            $result = [
                'msg' => '缺少请求参数',
                'ver' => '1.5.0',
                'data' =>[],
                'code' => '601'
            ];
            Yii::$app->end(json_encode($result));
        }else{
            $task = TCourseTask::find()->where('id=:id and del_flag=0',[':id'=>$taskId])->one();
            if (empty($task)) {
                $result = [
                    'msg' => '该任务不存在',
                    'ver' => '1.5.0',
                    'data' => array(),
                    'code' => '404'
                ];
                Yii::$app->end(json_encode($result));
            }
            $transaction = Yii::$app->db->beginTransaction();
            $flag = false;
            try {
                $classId = explode(',', $class_ids);
                $classIds = implode("','", $classId);
                $c_ids = "'".join("','", array_values($classId))."'";
                //1.发布时任务人数
                $sql = "SELECT count(*) as joinNum FROM t_course_member WHERE class_id IN ('".$classIds."') AND course_id =:courseId AND del_flag=0";
                $joinNum = Yii::$app->db->createCommand($sql)->bindValue(':courseId', $task->t_course_id)->queryOne();
                $update_time = date('Y-m-d H:i:s',time());

                $task->member_num = $joinNum['joinNum'];
                $task->task_status = 'activityStatus.ongoing';
                $task->class_id = $c_ids;
                $task->begin_time = $update_time;
                $task->end_time = '0000-00-00 00:00:00';
                $task->publish_by = $userId;
                $task->publish_time = $update_time;
                $task->update_by = $userId;
                $task->update_time = $update_time;
                $task->start_time = $startTime;
                $task->deadline = $deadline;
                if ($task->save()) {
                    $taskList = TCourseTaskList::find()->where('task_id=:taskId and del_flag=0',[':taskId'=>$taskId])->asArray()->all();
                    if (!empty($taskList)) {
                        $res = TCourseTaskList::updateAll(['task_status'=>'activityStatus.ongoing','update_by'=>$userId,'update_time'=>$update_time,'begin_time'=>$update_time,'end_time'=>'0000-00-00 00:00:00'],['task_id'=>$taskId,'del_flag'=>0]);
                        if ($res>0) {
                            $sql = "SELECT user_id FROM t_course_member WHERE course_id=:courseId AND del_flag=0 AND class_id IN ('".$classIds."')";
                            $students = Yii::$app->db->createCommand($sql)->bindValue(':courseId',$task->t_course_id)->queryColumn();
                            $s_model = new \app\models\TCourseTaskReport();
                            if(empty($students)){
                                //发布班级下没有学生
                                $transaction->rollback();
                                $result = [
                                    'msg' => '发布失败,发布班级下没有学生',
                                    'ver' => '1.5.0',
                                    'data' => [],
                                    'code' => '400'
                                ];
                                Yii::$app->end(json_encode($result));
                            }
                            foreach ($students as $k=>$v) {
                                $sql = "SELECT id FROM t_course_task_report WHERE task_id='".$taskId."' AND del_flag=0 AND create_by='".$v."'";
                                $res = Yii::$app->db->createCommand($sql)->queryAll();
                                if ($res) {
                                    continue;
                                }else{
                                    $uuid = Uuid::uuid();
                                    $model = clone $s_model;
                                    $model->id = $uuid;
                                    $model->task_id = $taskId;
                                    $model->report_status = 'reportStatus.notComplete';
                                    $model->create_by = $v;
                                    $model->create_time = $update_time;
                                    $model->old_id = $uuid;
                                    $model->del_flag = 0;
                                    if ($model->validate() && $model->save()) {
                                        $flag = true;
                                    } else {
                                        $flag = false;
                                        break;
                                    }
                                }
                            }
                            //修改任务状态
                            $sql="update t_course_schedule_task set status=:status,update_by=:release_by,update_time=:release_time,release_by=:release_by,release_time=:release_time where t_course_schedule_id=:schedule_id and task_id=:taskId and t_course_id=:courseId";
                            $res=\yii::$app->db->createCommand($sql)->bindValues([
                                ':status'=>'activityStatus.ongoing',
                                ':release_by'=>$userId,
                                ':release_time'=>$update_time,
                                ':schedule_id'=>$scheduleId,
                                ':courseId'=>$tcourseId,
                                ':taskId'=>$taskId
                            ])->execute();
                            if(!$res){
                                $flag=false;
                            }else{
                                $flag = true;
                            }
                        } else {
                            $transaction->rollback();
                            $result = [
                                'msg' => '发布失败',
                                'ver' => '1.5.0',
                                'data' => [],
                                'code' => '400'
                            ];
                            Yii::$app->end(json_encode($result));
                        }
                    } else {
                        $transaction->rollback();
                        $result = [
                            'msg' => '该任务下没有子任务，不能发布',
                            'ver' => '1.5.0',
                            'data' => [],
                            'code' => '401'
                        ];
                        Yii::$app->end(json_encode($result));
                    }
                }
            } catch (Exception $e) {
                $transaction->rollback();
                $result = [
                    'msg' => '异常',
                    'ver' => '1.5.0',
                    'data' => $e,
                    'code' => '500'
                ];
                Yii::$app->end(json_encode($result));
            }
            if ($flag) {
                $transaction->commit();
                $result = [
                    'msg' => '发布成功',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '200'
                ];
            }else{
                $transaction->rollback();
                $result = [
                    'msg' => '发布失败',
                    'ver' => '1.5.0',
                    'data' => [],
                    'code' => '400'
                ];
            }
            Yii::$app->end(json_encode($result));
        }
    }
}